<?php

use HyperDown\Parser;
//use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Auth;

require_once "kefu.php";

//快速模型添加修改操作
if (!function_exists('set_attributes')) {
    function set_attributes($model, $data)
    {
        foreach ($data as $item => $value) {
            if ($model->$item != $value) {
                $model->$item = $value;
            }
        }
        return $model;
    }
}
if (!function_exists('pagine')) {
    /**
     * @param $model
     * @param $page
     * @param $limit
     * @param $search
     * @param $count
     * @param string $order_by
     * @return array
     */
    function pagine($model, $page, $limit, $search, $count, $order_by = "created_at desc")
    {

        if (empty($page)) {
            $page = 0;
        }
        if (empty($limit)) {
            $limit = 15;
        }
        $query = $model::select('*');

        if ($count > 0) {
            if (!empty($search)) {
                foreach ($search as $key => $value) {
                    if ($value['name'] != 'ID') {
                        if (!empty($value['value'])) {
                            $query->where($value['name'], 'like', "%{$value['value']}%");
                        }
                    } else {
                        if (!empty($value['value'])) {
                            $query->where($value['name'], '=', $value['value']);
                        }
                    }
                }

            }
            $page_count = ($page - 1) * $limit;
            if ($count < $limit) {
                $limit = $count;
            }
            $order_by = explode(' ', $order_by);
            $query = $query->orderBy($order_by[0], $order_by[1])->offset($page_count)->limit($limit);

        }
        return $query;
    }
}
if (!function_exists('table_return')) {
    function table_return($code, $msg, $count = 0, $data = [])
    {
        $data = [
            'code' => $code,
            'msg' => $msg,
            'count' => $count,
            'data' => $data
        ];
        return response()->json($data);
    }
}
if (!function_exists('arraySort')) {
    function arraySort(&$array, $keys, $sort = SORT_DESC)
    {
        $keysValue = array_column($array, $keys);
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}

if (!function_exists('shuffle_assoc')) {
    function shuffle_assoc($list)
    {
        if (!is_array($list)) return $list;
        $keys = array_keys($list);
        shuffle($keys);
        $random = array();
        foreach ($keys as $key)
            $random[$key] = $list[$key];
        return $random;
    }
}
if (!function_exists('respone_return')) {
    function respone_return($code, $msg, $data = [])
    {
        if ($code == 0) {
            $data = [
                'code' => 0,
                'msg' => $msg
            ];
            return response()->json($data);
        }

        $data = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];
        return response()->json($data);
    }
}
if (!function_exists('ajax_return')) {
    /**
     * ajax返回数据
     *
     * @param string $data 需要返回的数据
     * @param int $status_code
     * @return \Illuminate\Http\JsonResponse
     */
    function ajax_return($status_code = 200, $data = '')
    {
        //如果如果是错误 返回错误信息
        if ($status_code != 200) {
            //增加status_code
            $data = ['status_code' => $status_code, 'message' => $data,];
            return response()->json($data, $status_code);
        }
        //如果是对象 先转成数组
        if (is_object($data)) {
            $data = $data->toArray();
        }
        /**
         * 将数组递归转字符串
         * @param array $arr 需要转的数组
         * @return array       转换后的数组
         */
        function to_string($arr)
        {
            // app 禁止使用和为了统一字段做的判断
            $reserved_words = [];
            foreach ($arr as $k => $v) {
                //如果是对象先转数组
                if (is_object($v)) {
                    $v = $v->toArray();
                }
                //如果是数组；则递归转字符串
                if (is_array($v)) {
                    $arr[$k] = to_string($v);
                } else {
                    //判断是否有移动端禁止使用的字段
                    in_array($k, $reserved_words, true) && die('不允许使用【' . $k . '】这个键名 —— 此提示是helper.php 中的ajaxReturn函数返回的');
                    //转成字符串类型
                    $arr[$k] = strval($v);
                }
            }
            return $arr;
        }

        //判断是否有返回的数据
        if (is_array($data)) {
            //先把所有字段都转成字符串类型
            $data = to_string($data);
        }
        return response()->json($data, $status_code);
    }
}
//if ( !function_exists('send_email') ) {
//    /**
//     * 发送邮件函数
//     *
//     * @param $email            收件人邮箱  如果群发 则传入数组
//     * @param $name             收件人名称
//     * @param $subject          标题
//     * @param array  $data      邮件模板中用的变量 示例：['name'=>'帅白','phone'=>'110']
//     * @param string $template  邮件模板
//     * @return array            发送状态
//     */
//    function send_email($email, $name, $subject, $data = [], $template = 'emails.test')
//    {
//        Mail::send($template, $data, function ($message) use ($email, $name, $subject) {
//            //如果是数组；则群发邮件
//            if (is_array($email)) {
//                foreach ($email as $k => $v) {
//                    $message->to($v, $name)->subject($subject);
//                }
//            } else {
//                $message->to($email, $name)->subject($subject);
//            }
//        });
//        if (count(Mail::failures()) > 0) {
//            $data = array('code' => 0, 'msg' => '邮件发送失败');
//        } else {
//            $data = array('code' => 200, 'msg' => '邮件发送成功');
//        }
//        return $data;
//    }
//}

if (!function_exists('upload')) {
    /**
     * 上传文件函数
     *
     * @param $file             表单的name名
     * @param string $path 上传的路径
     * @param bool $childPath 是否根据日期生成子目录
     * @return array            上传的状态
     */
    function upload($file, $path = 'upload', $childPath = true)
    {
        //判断请求中是否包含name=file的上传文件
        if (!request()->hasFile($file)) {
            $data = ['code' => 1, 'msg' => '上传文件为空'];
            return $data;
        }
        $file = request()->file($file);
        //判断文件上传过程中是否出错
        if (!$file->isValid()) {
            $data = ['code' => 0, 'msg' => '文件上传出错'];
            return $data;
        }
        //兼容性的处理路径的问题
        if ($childPath == true) {
            $path = './' . trim($path, './') . '/' . date('Ymd') . '/';
        } else {
            $path = './' . trim($path, './') . '/';
        }
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        //获取上传的文件名
        $oldName = $file->getClientOriginalName();
        //组合新的文件名
        $newName = uniqid() . '.' . $file->getClientOriginalExtension();
        //上传失败
        if (!$file->move($path, $newName)) {
            $data = ['code' => 2, 'msg' => '保存文件失败'];
            return $data;
        }
        //上传成功
        $data = ['code' => 200, 'msg' => '上传成功', 'data' => ['old_name' => $oldName, 'new_name' => $newName, 'path' => trim($path, '.')]];
        return $data;
    }
}

if (!function_exists('get_uid')) {
    /**
     * 返回登录的用户id
     *
     * @return mixed 用户id
     */
    function get_uid()
    {
        return Auth::id();
    }
}

if (!function_exists('save_to_file')) {
    /**
     * 将数组已json格式写入文件
     * @param string $fileName 文件名
     * @param array $data 数组
     */
    function save_to_file($fileName = 'test', $data = array())
    {
        $path = storage_path('tmp' . DIRECTORY_SEPARATOR);
        is_dir($path) || mkdir($path);
        $fileName = str_replace('.php', '', $fileName);
        $fileName = $path . $fileName . '_' . date('Y-m-d_H-i-s', time()) . '.php';
        file_put_contents($fileName, json_encode($data));
    }
}

if (!function_exists('re_substr')) {
    /**
     * 字符串截取，支持中文和其他编码
     *
     * @param string $str 需要转换的字符串
     * @param integer $start 开始位置
     * @param string $length 截取长度
     * @param boolean $suffix 截断显示字符
     * @param string $charset 编码格式
     * @return string
     */
    function re_substr($str, $start = 0, $length, $suffix = true, $charset = "utf-8")
    {
        $str=str_replace(' ','',$str);
        $slice = mb_substr($str, $start, $length, $charset);
        $omit = mb_strlen($str) >= $length ? '...' : '';
        return $suffix ? $slice . $omit : $slice;
    }
}

if (!function_exists('Add_text_water')) {
    /**
     * 给图片添加文字水印
     *
     * @param $file
     * @param $text
     * @param string $color
     * @return mixed
     */
    function Add_text_water($file, $text, $color = '#0B94C1')
    {
//        $image = Image::make($file);
//        $image->text($text, $image->width()-20, $image->height()-30, function($font) use($color) {
//            $font->file(public_path('fonts/msyh.ttf'));
//            $font->size(15);
//            $font->color($color);
//            $font->align('right');
//            $font->valign('bottom');
//        });
//        $image->save($file);
//        return $image;
    }
}

if (!function_exists('word_time')) {
    /**
     * 把日期或者时间戳转为距离现在的时间
     *
     * @param $time
     * @return bool|string
     */
    function word_time($time)
    {
        // 如果是日期格式的时间;则先转为时间戳
        if (!is_integer($time)) {
            $time = strtotime($time);
        }
        $int = time() - $time;
        if ($int <= 2) {
            $str = sprintf('刚刚', $int);
        } elseif ($int < 60) {
            $str = sprintf('%d秒前', $int);
        } elseif ($int < 3600) {
            $str = sprintf('%d分钟前', floor($int / 60));
        } elseif ($int < 86400) {
            $str = sprintf('%d小时前', floor($int / 3600));
        } elseif ($int < 1728000) {
            $str = sprintf('%d天前', floor($int / 86400));
        } else {
            $str = date('Y-m-d H:i:s', $time);
        }
        return $str;
    }
}

if (!function_exists('markdown_to_html')) {
    /**
     * 把markdown转为html
     *
     * @param $markdown
     * @return mixed|string
     */
    function markdown_to_html($markdown)
    {
        // 正则匹配到全部的iframe
        preg_match_all('/&lt;iframe.*iframe&gt;/', $markdown, $iframe);
        // 如果有iframe 则先替换为临时字符串
        if (!empty($iframe[0])) {
            $tmp = [];
            // 组合临时字符串
            foreach ($iframe[0] as $k => $v) {
                $tmp[] = '【iframe' . $k . '】';
            }
            // 替换临时字符串
            $markdown = str_replace($iframe[0], $tmp, $markdown);
            // 讲iframe转义
            $replace = array_map(function ($v) {
                return htmlspecialchars_decode($v);
            }, $iframe[0]);
        }
        // markdown转html
        $parser = new Parser();
        $html = $parser->makeHtml($markdown);
        $html = str_replace('<code class="', '<code class="lang-', $html);
        // 将临时字符串替换为iframe
        if (!empty($iframe[0])) {
            $html = str_replace($tmp, $replace, $html);
        }
        return $html;
    }
}

if (!function_exists('strip_html_tags')) {
    /**
     * 删除指定标签
     *
     * @param array $tags 删除的标签  数组形式
     * @param string $str html字符串
     * @param bool $content true保留标签的内容text
     * @return mixed
     */
    function strip_html_tags($tags, $str, $content = true)
    {
        $html = [];
        // 是否保留标签内的text字符
        if ($content) {
            foreach ($tags as $tag) {
                $html[] = '/(<' . $tag . '.*?>(.|\n)*?<\/' . $tag . '>)/is';
            }
        } else {
            foreach ($tags as $tag) {
                $html[] = "/(<(?:\/" . $tag . "|" . $tag . ")[^>]*>)/is";
            }
        }
        $data = preg_replace($html, '', $str);
        return $data;
    }
}

if (!function_exists('curl_get_contents')) {
    /**
     * 使用curl获取远程数据
     * @param string $url url连接
     * @return string      获取到的数据
     */
    function curl_get_contents($url)
    {
        set_time_limit(0);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);                //设置访问的url地址
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);               //设置超时
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);   //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']);        //设置 referer
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);          //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }
}
if (!function_exists('get_ip')) {
    function get_ip()
    {
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        $res = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '';
        return $res;
    }
}
if (!function_exists('getInvId')) {
    /**
     * 递归获取所有下级
     * @param $data 标准树数据
     * @param $invId 要获取下级的id
     * @return array
     */
//    function getInvId($data, $invId=0)
//    {
//        static $arr = [];
//        foreach ($data as $key => &$val) {
//            if ($val['pid'] == $invId) {
//                $arr[] = $val;
//                getInvId($data, $val['id']);
//                unset($val);
//            }
//        }
//        return $arr;
//    }

    function getInvId($data, $invId)
    {
        die('324');
        static $arr = [];
        foreach ($data as $key => $val) {
            if ($val['pid'] == $invId) {
                $arr[] = $val['id'];
                getInvId($data, $val['id']);
            }
        }
        return $arr;
    }
}

if (!function_exists('send_email')) {
    /**
     * 发送邮箱
     * @param $type 类型 0=普通文本 1=带附件或模板变量的
     * @param $params 参数
     *
     * $params=[
     * $address='待发送邮箱账号',
     * $text='主题',
     * $attachments=[
     * storage_path('xls/files/test.xls'),//附件数组
     * storage_path('xls/files/test2.xls')
     * ],
     * $param=[ //传递至视图变量
     * 'img'=>'图片地址',
     * 'username'=>'用户名',
     * 'code'=>'验证码',
     * 'token'=>'唯一标识 这几个参数是传递到页面的可以随便填写'
     * ]
     * ];
     */
    function send_email($type)
    {

        try{
            $params = [
                'subject' => 'hello',
                'address' => ['544867814@qq.com', '601536708@qq.com'],
                'text' => '你好你的编号' . mt_rand(10000, 100000),
                'attachments' => [
                    public_path('m3u8.html'),
                ],
                'param' => [
                    'img' => '图片地址',
                    'username' => '用户名',
                    'code' => '验证码',
                    'token' => '唯一标识 这几个参数是传递到页面的可以随便填写'
                ]
            ];

            $subject = isset($params['subject']) ? $params['subject'] : '';
            $email_address = isset($params['address']) ? $params['address'] : '';
            $text = isset($params['text']) ? $params['text'] : '';
            $attachments = isset($params['attachments']) ? $params['attachments'] : '';
            $param = isset($params['param']) ? $params['param'] : '';
            if (empty($email_address) || empty($subject)) {

                throw new Exception('send email Lack of key parameters');
            }
            switch ($type) {
                case 0:
                    if (!empty($email_address)) {
                        if (is_array($email_address)) {
                            foreach ($email_address as $item) {
                                try {
                                    Mail::raw($text, function ($message) use ($item, $subject) {
                                        $message->to($item)->subject($subject);
                                    });
                                } catch (\Exception $e) {
                                    throw new Exception($e->getMessage());
                                }
                            }
                        } else if (is_string($email_address)) {
                            Mail::raw($text, function ($message) use ($email_address, $subject) {
                                $message->to($email_address)->subject($subject);
                            });
                        }
                    }
                    break;
                case 1:
                    Mail::send('emails.test', $param, function ($message) use ($attachments, $email_address, $text) {
                        $message->to($email_address)->subject($text);
                        // 在邮件中上传附件
                        if (!empty($attachments)) {
                            foreach ($attachments as $attachment) {
                                $message->attach($attachment);
                            }
                        }
                    });
                    break;

            }
        }catch (\Exception $e){
            dd($e->getMessage());
        }


    }
}
if (!function_exists('redis')) {
    /**
     * redis的便捷操作方法
     *
     * @param $key
     * @param null $value
     * @param null $expire
     * @return bool|string
     */
    function redis($key = null, $value = null, $expire = null)
    {
//        if (is_null($key)) {
//            return app('redis');
//        }
//
//        if (is_null($value)) {
//            $content = Redis::get($key);
//            if (is_null($content)) {
//                return null;
//            }
//            return is_null($content) ? null : unserialize($content);
//        }
//
//        Redis::set($key, serialize($value));
//        if (! is_null($expire)) {
//            Redis::expire($key, $expire);
//        }
    }
}
if (!function_exists('requestGet')) {
    /**
     * curl 模拟 GET 请求
     * @param string $url 请求的URL
     * @param bool|true $ssl 是否启用 ssl证书验证
     * @param array $headers 设置 HTTP 头字段的数组，格式： array('Content-type: text/plain', 'Content-length: 100')
     * @return bool|mixed
     *
     */
    function requestGet($url, $ssl = false, $headers = array())
    {

        # curl完成初始化
        $curl = curl_init();

        # curl 选项设置
        curl_setopt($curl, CURLOPT_URL, $url); //需要获取的URL地址

        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36';
        curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);   # 在HTTP请求中包含一个"User-Agent: "头的字符串，声明用什么浏览器来打开目标网页
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:8.8.8.8', 'CLIENT-IP:23.88.113.61'));  //构造IP
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);     # TRUE 时将会根据服务器返回 HTTP 头中的 "Location: " 重定向。

        curl_setopt($curl, CURLOPT_AUTOREFERER, true);        # TRUE 时将根据 Location: 重定向时，自动设置 header 中的Referer:信息。

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);              # 设置超时时间
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Connection:close'
        , 'Accept-Language:zh-CN,zh;q=0.9'
        , 'Accept-Encoding:gzip, deflate'
        ));
        curl_setopt($curl, CURLOPT_ENCODING, '');
        # HTTP请求头中"Accept-Encoding: "的值。 这使得能够解码响应的内容。 支持的编码有"identity"，"deflate"和"gzip"。如果为空字符串""，会发送所有支持的编码类型

        if ($headers) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);  # 设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100')
        }

        # SSL相关，https需开启
        if ($ssl) {
            curl_setopt($curl, CURLOPT_CAINFO, '/cert/ca.crt');  # CA 证书地址
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);    # 禁用后cURL将终止从服务端进行验证
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
            # 设置为 1 是检查服务器SSL证书中是否存在一个公用名；设置成 2，会检查公用名是否存在，并且是否与提供的主机名匹配；0 为不检查名称。 在生产环境中，这个值应该是 2（默认值）。
            # 公用名(Common Name)一般来讲就是填写你将要申请SSL证书的域名 (domain)或子域名(sub domain)
        } else {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);    # 禁用后cURL将终止从服务端进行验证，默认为 true
        }

        curl_setopt($curl, CURLOPT_HEADER, false);             # 是否处理响应头，启用时会将头文件的信息作为数据流输出

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);      # TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出。

        # 执行 curl 会话
        $response = curl_exec($curl);

        if (false === $response) {
            echo '<br>', curl_error($curl), '<br>';
            return false;
        }
        #关闭 curl会话
        curl_close($curl);
        return $response;
    }
}
if (!function_exists('curl_request')) {
    function curl_request($url, $post = '', $cookie = '', $returnCookie = 0)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if ($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if ($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);

        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if ($returnCookie) {
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie'] = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        } else {
            return $data;
        }
    }

}
if (!function_exists('curl')) {
    function curl($url, $method = 'GET', $fields = [], $headers = [], $auth = false)
    {
        //如果是get的获取方式，拼接参数到url上
        if ($method == "GET") {
            $fields_string = http_build_query($fields);
            $url = $url . "?" . $fields_string;
        }
        $curl = curl_init($url); //初始化
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); //设定HTTP请求方式
        curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_VERBOSE, 1);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] = "Cache-Control: max-age=0";
        $header[] = "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Pragma: "; // browsers keep this blank.
        curl_setopt($curl, CURLOPT_HTTPHEADER, array_merge($header, $headers)); //和参数中的header一起传递过去
        if ($auth) {
            curl_setopt($curl, CURLOPT_USERPWD, "$auth");
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        }
        if ($fields) {
            //POST
            if ($method == "POST") {//单独对POST方法设置参数传递
                $fields_string = http_build_query($fields);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
            } else {
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
            }
        }
        $response = curl_exec($curl); //执行curl
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $header_string = substr($response, 0, $header_size);
        $body = substr($response, $header_size);
        $header_rows = explode(PHP_EOL, $header_string);
        foreach ($header_rows as $key => $value) {
            $header_rows[$key] = trim($header_rows[$key]);
        }
        $i = 0;
        foreach ((array)$header_rows as $hr) {
            $colonpos = strpos($hr, ':');
            $key = $colonpos !== false ? substr($hr, 0, $colonpos) : (int)$i++;
            $headers[$key] = $colonpos !== false ? trim(substr($hr, $colonpos + 1)) : $hr;
        }
        $j = 0;
        foreach ((array)$headers as $key => $val) {
            $vals = explode(';', $val);
            if (count($vals) >= 2) {
                unset($headers[$key]);
                foreach ($vals as $vk => $vv) {
                    $equalpos = strpos($vv, '=');
                    $vkey = $equalpos !== false ? trim(substr($vv, 0, $equalpos)) : (int)$j++;
                    $headers[$key][$vkey] = $equalpos !== false ? trim(substr($vv, $equalpos + 1)) : $vv;
                }
            }
        }
        curl_close($curl);
        return array($body, $headers); //最终返回 result[0]为body,result[1]为header
    }
}
function getHost($url){
    if ($url == "127.0.0.1" || $url == "localhost") {
        return $url;
    }
    $is_include_http = strpos($url, "http");

    if ($is_include_http === false) {
        $url = "http://{$url}";
    }
    $url = strtolower($url);  //首先转成小写
    $hosts = parse_url($url);
    return $hosts['scheme']."://".$hosts['host'];
}
//获取顶级域名
function getTopHost($url)
{
    if ($url == "127.0.0.1" || $url == "localhost") {
        return $url;
    }
    $is_include_http = strpos($url, "http");

    if ($is_include_http === false) {
        $url = "http://{$url}";
    }
    $url = strtolower($url);  //首先转成小写
    $hosts = parse_url($url);
    $host = $hosts['host'];

    //查看是几级域名
    $data = explode('.', $host);
    $n = count($data);
    //判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
    if (($n > 2) && preg_match($preg, $host)) {
        //双后缀取后3位
        $host = $data[$n - 3] . '.' . $data[$n - 2] . '.' . $data[$n - 1];
    } else {
        //非双后缀取后两位
        $host = $data[$n - 2] . '.' . $data[$n - 1];
    }
    return $host;
}

function isValidUrl($url){
    return preg_match('/^http[s]?:\/\/'.
            '(([0-9]{1,3}\.){3}[0-9]{1,3}'. // IP形式的URL- 199.194.52.184
            '|'. // 允许IP和DOMAIN（域名）
            '([0-9a-z_!~*\'()-]+\.)*'. // 域名- www.
            '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.'. // 二级域名
            '[a-z]{2,6})'.  // first level domain- .com or .museum
            '(:[0-9]{1,4})?'.  // 端口- :80
            '((\/\?)|'.  // a slash isn't required if there is no file name
            '(\/[0-9a-zA-Z_!~\'
\.;\?:@&=\+\$,%#-\/^\*\|]*)?)$/',
            $url) == 1;
}

//判断获取数据的是不是爬虫|机器人
function is_spider() {
    $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";


    $ua=strtolower($ua);

    if (preg_match('#(bot|spider|mj12bot|dotbot|bing|msnbot|bingbot|googlebot|yahoo|slurp|sogou|yodaoBot|semrushbot|ahrefsbot)#i', $ua)){
        return true;
    }
    return false;
}


/**
 * 设置水印  zst
 * @param $imgSrc           待处理图片全路径
 * @param $markImg          水印图片全路径
 * @param $watermark_file   处理完毕水印图片路径
 * @param $markType         图片添加水印的方式，img代表以图片方式，text代表以文字方式添加水印
 * @param int $markPos 图片水印添加的位置默认为0，取值范围：0~9  0：随机位置，在1~8之间随机选取一个位置 1：顶部居左 2：顶部居中 3：顶部居右 4：左边居中 5：图片中心 6：右边居中 7：底部居左 8：底部居中 9：底部居右
 * @param $markText         给图片添加的水印文字
 * @param $TextColor        水印文字的字体颜色
 * @param $fontType         具体的字体库，可带相对目录地址
 */
function  setWater($imgSrc, $markImg, $watermark_file, $markType, $markPos, $markText, $TextColor, $fontType)
{

    $srcInfo = @getimagesize($imgSrc);
    $srcImg_w = $srcInfo[0];
    $srcImg_h = $srcInfo[1];

    switch ($srcInfo[2]) {
        case 1:
            $srcim = imagecreatefromgif($imgSrc);
            break;
        case 2:
            $srcim = imagecreatefromjpeg($imgSrc);
            break;
        case 3:
            $srcim = imagecreatefrompng($imgSrc);
            break;
        default:
            throw new \Exception("不支持的图片文件类型");
            exit;
    }

    /*合成水印路径为空就覆盖原图*/
    if (empty($watermark_file)) {
        $watermark_file = $imgSrc;
    }

    if (!strcmp($markType, "img")) {
        if (!file_exists($markImg) || empty($markImg)) {
            return;
        }

        $markImgInfo = @getimagesize($markImg);
        $markImg_w = $markImgInfo[0];
        $markImg_h = $markImgInfo[1];

        if ($srcImg_w < $markImg_w || $srcImg_h < $markImg_h) {
            return;
        }

        switch ($markImgInfo[2]) {
            case 1:
                $markim = imagecreatefromgif($markImg);
                break;
            case 2:
                $markim = imagecreatefromjpeg($markImg);
                break;
            case 3:
                $markim = imagecreatefrompng($markImg);
                break;
            default:
                die("不支持的水印图片文件类型");
                exit;
        }

        $logow = $markImg_w;
        $logoh = $markImg_h;
    }

    if (!strcmp($markType, "text")) {
        $fontSize = 16;
        if (!empty($markText)) {
            if (!file_exists($fontType)) {
                return;
            }
        } else {
            return;
        }

        $box = @imagettfbbox($fontSize, 0, $fontType, $markText);
        $logow = max($box[2], $box[4]) - min($box[0], $box[6]);
        $logoh = max($box[1], $box[3]) - min($box[5], $box[7]);
    }

    if ($markPos == 0) {
        $markPos = rand(1, 9);
    }

    switch ($markPos) {
        case 1:
            $x = +5;
            $y = +5;
            break;
        case 2:
            $x =    ($srcImg_w - $logow) / 2;
            $y = +5;
            break;
        case 3:
            $x = $srcImg_w - $logow - 5;
            $y = +15;
            break;
        case 4:
            $x = +5;
            $y = ($srcImg_h - $logoh) / 2;
            break;
        case 5:
            $x = ($srcImg_w - $logow) / 2;
            $y = ($srcImg_h - $logoh) / 2;
            break;
        case 6:
            $x = $srcImg_w - $logow - 5;
            $y = ($srcImg_h - $logoh) / 2;
            break;
        case 7:
            $x = +5;
            $y = $srcImg_h - $logoh - 5;
            break;
        case 8:
            $x = ($srcImg_w - $logow) / 2;
            $y = $srcImg_h - $logoh - 5;
            break;
        case 9:
            $x = $srcImg_w - $logow - 5;
            $y = $srcImg_h - $logoh - 5;
            break;
        default:
            die("此位置不支持");
            exit;
    }

    $dst_img = @imagecreatetruecolor($srcImg_w, $srcImg_h);

    imagecopy($dst_img, $srcim, 0, 0, 0, 0, $srcImg_w, $srcImg_h);

    if (!strcmp($markType, "img")) {
        imagecopy($dst_img, $markim, $x, $y, 0, 0, $logow, $logoh);
        imagedestroy($markim);
    }

    if (!strcmp($markType, "text")) {
        $rgb = explode(',', $TextColor);

        $color = imagecolorallocate($dst_img, $rgb[0], $rgb[1], $rgb[2]);
        imagettftext($dst_img, $fontSize, 0, $x, $y, $color, $fontType, $markText);
    }

    switch ($srcInfo[2]) {
        case 1:
            imagegif($dst_img, $watermark_file);
            break;
        case 2:
            imagejpeg($dst_img, $watermark_file);
            break;
        case 3:
            imagepng($dst_img, $watermark_file);
            break;
        default:
            die("不支持的水印图片文件类型");
            exit;
    }

    unlink($markImg);
    imagedestroy($dst_img);
    imagedestroy($srcim);
}